//
//  LogisticsCtr.swift
//  smosky
//
//  Created by zhuxietong on 2018/7/30.
//  Copyright © 2018年 tianrun. All rights reserved.
//

import Foundation
import soapp
import Eelay
import AsyncDisplayKit

enum LogisticsStatus:String
{
    
    case 途中  = "0"
    case 揽件 = "1"
    case 疑难 = "2"
    case 签收 = "3"
    case 退签 = "4"
    case 派件 = "5"
    case 退回 = "6"
    
    case none = ""
    
    var name:String{
        get{
            switch self {
            case .途中:
                return "运输途中".loc
            case .揽件:
                return "物流公司已揽件".loc
            case .疑难:
                return "货物寄送过程出了问题".loc
            case .签收:
                return "已签收".loc
            case .退签:
                return "该物流已退签收".loc
            case .派件:
                return "派件中".loc
            case .退回:
                return "退回发件人的途中".loc
            case .none:
                return "未知".loc
            }
        }
    }
    
//    0：在途，即货物处于运输过程中；
//    1：揽件，货物已由快递公司揽收并且产生了第一条跟踪信息；
//    2：疑难，货物寄送过程出了问题；
//    3：签收，收件人已签收；
//    4：退签，即货物由于用户拒签、超区等原因退回，而且发件人已经签收；
//    5：派件，即快递正在进行同城派件；
//    6：退回，货物正处于退回发件人的途中；
}

public class LogisticsCtr: ASListController {
    
    public var sections:TP.section{
        get{
            let sec = [
                [
                    [
                        "cellID":"head",
                        "__model":mo.detail,
                        "state":mo.detail["state",""]
                    ],
                ],
                [
                    
                ]
            ]
            return sec
        }
    }
    
    public let selector:TP.selector = [
        "cellID<head>":HeadCell.self,
        "cellID<message>":EmptyCell.self,
        "<default>":LogCell.self,
    ]
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        mo_request_send()
        title = "物流信息".loc
        tableNode.backgroundColor = UIColor.table_bg_color
    }
    
    public var logs:NSMutableArray = NSMutableArray(){
        didSet{
            if let obj = logs.firstObject as? NSMutableDictionary{
                obj["__first"] = FK.YES
            }
            if let obj = logs.lastObject as? NSMutableDictionary{
                obj["__last"] = FK.YES
            }
            
            tableNode.load(sections: sections, selector: selector)
            tableNode.model["section1"] = logs
            tableNode.reloadData()
        }
    }
    
    func invalidLog(message:String){
        tableNode.load(sections: sections, selector: selector)
        tableNode.model["section1"] = [
            ["cellID":"message","message":message]
        ].mutable_array
        tableNode.reloadData()

    }
    
    override public func mo_request_send() {
        
        weak var wself = self
        loadingV.loading()
        
//        print("+++__|\(mo.model)")
        let sn = mo.model.possible("order.expresssn","expresssn","rexpresssn", default: "")
        let com = mo.model.possible("order.expresscom","expresscom","rexpresscom", default: "")
        let express = mo.model.possible("order.express","express","rexpress", default: "")
        
        
        JoTask().get.log._surl(.订单物流).params(["expresssn":sn,"express":express,"expresscom":com]).json_handle { (status, msg, obj, resp) in
            wself?.loadingV.dismiss()
            if status.isSuccess{
                if let dict = obj as? NSMutableDictionary{
                    wself?.mo.detail = dict
                    let list = DataNode.path(node: "list", dict, value: NSMutableArray())
                    
                    if list.count < 1
                    {
                        wself?.invalidLog(message: "未查到相关物流信息".loc)
                    }
                    else{
                        wself?.logs = list
                    }
                    return
                }
            }
            wself?.invalidLog(message: msg)

            }.run()
    }

    
    
}
extension LogisticsCtr{
    
    class LogCell: JoCellNode {
        let indicatorV = ASDisplayNode()
        let textV = JoTextNode()
        let dateL = JoTextNode()
        let timeL = JoTextNode()
        let line1 = ASDisplayNode()
        let line2 = ASDisplayNode()
        
        override func addLayoutRules() {
            backgroundColor = ._cellBackground
        }
        
        
        var color:UIColor{
            get{
                if mo.model["__first",""] == FK.YES
                {
                    return UIColor._foreground
                }
                return UIColor.color(light: "#666", dark: "#999")
            }
        }
  
        
        override func mo_model_reload() {
            
            let timeStr = mo.model["time",""]
            let time = timeStringToDate(timeStr, format: "yyyy-MM-dd HH:mm:ss")
            timeL.attributedText = time["HH:mm"].ui.font16.color(color: color).center.astring
            dateL.attributedText = time["yyyy-MM-dd"].ui.font11.color(color: color).center.astring
            textV.attributedText = mo.model["step",""].ui.font12.color(color: color).lineSpace(6).astring

            if mo.model["__first",""] == FK.YES
            {
                line1.backgroundColor = .clear
            }else{
                line1.backgroundColor = UIColor(shex: "#999")
            }
            
            if mo.model["__last",""] == FK.YES
            {
                line2.backgroundColor = .clear
            }else{
                line2.backgroundColor = UIColor(shex: "#999")
            }
                        
        }
        
        override func specGetter() -> _Spec {
            
            let timeSpec:_Spec = _Spec.stack(["v|2",&-.center], childs: [
                line1[.>"18",_grow(1),1],
                timeL[70],
                dateL["15",70],
                line2[.>"18",_grow(1),1]
            ])
            return _Spec.stack([[0,AppTheme.edge],"h|10",_nowrap,&-.stretch], childs: [
                timeSpec,
                textV[_shrink(1)],
                ])
        }
    }
    
    
    class EmptyCell:JoCellNode{
        let lable = ASTextNode2()
        
        override func mo_model_reload() {
            lable.attributedText = mo.model["message","未知错误".loc].ui.cl_666.font14.center.astring
        }
        override func specGetter() -> _Spec {
            let height = Sheight - TP.topHeight - 73  - 20 - 40 - 40
            return _Spec.stack(["v",&-.stretch,_justfy(.center),"\(height)"], childs: [
                lable.Spec
            ])
        }
    }
    
    class HeadCell: JoCellNode {
        let imgV = JoImageNode()
        let statusL = ASTextNode2()
        let compL = ASTextNode2()
        let noL = ASTextNode2()
        
        let contentBk = ASDisplayNode()
        override func mo_model_reload() {
            backgroundColor = UIColor.table_bg_color
            
            statusL.maximumNumberOfLines = 1
            compL.maximumNumberOfLines = 1
            noL.maximumNumberOfLines = 1

            let object = DataNode.path(node: "__model", mo.model, value: NSMutableDictionary())
            
            let status = LogisticsStatus(rawValue: mo.model["state",""]) ?? .none
            statusL.attributedText = "\("物流状态".loc): ".ui.font13.color(color: ._foreground).astring + status.name.ui.color(color: ___shop.tint).font13.astring

            imgV.img_url = object["expressimg",""]
            compL.attributedText = "\("快递公司".loc): ".ui.font13.color(color: ._foreground).astring + object["expresscom",""].ui.bfont13.color(color: ._foreground).astring
            
            noL.attributedText = "\("快递单号".loc): ".ui.font13.color(color: ._foreground).astring + object["expresssn",""].ui.bfont12.color(color: ._foreground).astring
            
            noL.truncationMode = .byTruncatingTail
            contentBk.backgroundColor = UIColor._cellBackground
        }
        
        override func specGetter() -> _Spec {
            let w = Swidth - 2.0 * AppTheme.edge - 72.0 - 10
            let contentSpec:_Spec = .stack(["h|10",&-.flex_start,_nowrap,[14,AppTheme.edge]], childs: [
                imgV["72",72],
                .stack(["v|5",&-.stretch,_justfy(.flex_start),_grow(1),_shrink(1)], childs: [
//                    statusL.Spec,
                    compL.Spec,
                    noL[w]
                    ])
                ])
            
            let bk:_Spec = _Spec.back([[10,0]], over: contentSpec, back: contentBk.Spec)
            
            return bk
            
            
        }
    }
}
